package spring.cloud.tasks.executor.executor.task.task_item_execute;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import spring.cloud.tasks.executor.executor.task.execute_runtime_context.TaskItemExecuteRuntimeContext;


@Slf4j
@Setter
@Getter
public
class TaskItemExecuteTimeoutTask implements Runnable {

    private String threadName;

    public TaskItemExecuteTimeoutTask(String threadName) {
        this.threadName = threadName;
    }


    @Override
    public void run() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                timeOut(threadName);
            }
        }).start();
    }

    private void timeOut(String threadName) {
        try {
            Thread thread = getThreadByName(threadName);
            if (thread != null) {
                TaskItemExecuteThread taskItemExecuteThread = (TaskItemExecuteThread) thread;
                TaskItemExecuteTask taskItemExecuteTask = taskItemExecuteThread.getTaskItemExecuteTask();
                if (taskItemExecuteTask != null) {
                    TaskItemExecute taskItemExecute = taskItemExecuteTask.getTaskItemExecute();
                    if (taskItemExecute != null) {
                        if (taskItemExecute.setTimeoutWhenStatusInit()) {
                            log.info(String.format("任务超时执行KILL任务线程" + TaskItemExecuteRuntimeContext.getTaskItemId(taskItemExecute)));
                            // 强杀
                            TaskItemExecuteTaskKill.kill(taskItemExecuteTask);
                        }
                    }

                }

            }

        } catch (Throwable t) {
            log.error("强杀任务线程失败", t);
        }
    }

    public Thread getThreadByName(String threadName) {
        for (Thread thread : Thread.getAllStackTraces().keySet()) {
            if (thread.getName().equals(threadName)) {

                return thread;
            }
        }
        return null;
    }

}
